﻿#include "mutex.h"
#include "remote_obj_error.h"

using namespace RemoteObj;

Mutex::Mutex()
{
    _mutex = CreateMutex(NULL, FALSE, NULL);
}

Mutex::~Mutex()
{
    BOOL ret = CloseHandle(_mutex);
    if (0 != ret)
    {
        _mutex = NULL;
    }
}

int32_t Mutex::lock(uint32_t millisecond)
{
    if (NULL == _mutex)
    {
        return E_REMOTEOBJ_NULL_POINTER;
    }

    DWORD ret = WaitForSingleObject(_mutex, millisecond);
    if (WAIT_OBJECT_0 == ret)
    {
        return 0;
    }
    else if (WAIT_TIMEOUT == ret)
    {
        return E_REMOTEOBJ_TIMEOUT;
    }
    else
    {
        return E_REMOTEOBJ_SYSERROR;
    }
}

int32_t Mutex::unlock()
{
    BOOL ret = FALSE;

    if (NULL != _mutex)
    {
        ret = ReleaseMutex(_mutex);
    }
    return (0 != ret ? 0 : E_REMOTEOBJ_SYSERROR);
}
